package com.chen.authority.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.authority.common.model.PageQo;
import com.chen.authority.common.util.GenUtil;
import com.chen.authority.mapper.CodeGenerateMapper;
import com.chen.authority.service.CodeGenerateService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成Service业务层处理
 *
 * @author chengy
 * @date 2022-11-19
 */
@Service
@RequiredArgsConstructor
public class CodeGenerateServiceImpl implements CodeGenerateService {

    private final CodeGenerateMapper codeGenerateMapper;

    @Override
    public Page<Map<String, Object>> pageQueryTableList(PageQo pageQo, String name, String description) {
        return codeGenerateMapper.selectTableListByPageAndCondition(pageQo.build(), name, description);
    }

    @Override
    public byte[] generateCode(String[] names) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for(String name : names){
            //查询表信息
            Map<String, String> table = codeGenerateMapper.selectTableByName(name);
            //查询列信息
            List<Map<String, String>> columns = codeGenerateMapper.selectColumnsByTableName(name);
            //生成代码
            GenUtil.generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

}